package org.jiajie.coffeecodes.concurrent.pattern.copy.on.write;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 路由表信息
 *
 * @author jay
 */
public class RouterTable {
    /**
     * Key: 接口名
     * Value: 路由集合
     */
    ConcurrentHashMap<String, CopyOnWriteArraySet<Router>> rt = new ConcurrentHashMap<>();

    /**
     * 根据接口名称获取路由表
     *
     * @param iface iface
     * @return 路由表
     */
    public Set<Router> get(String iface) {
        return rt.get(iface);
    }

    /**
     * 删除路由
     *
     * @param router 路由
     */
    public void remove(Router router) {
        Set<Router> set = rt.get(router.getIface());
        if (set != null) {
            set.remove(router);
        }
    }

    /**
     * 添加路由
     *
     * @param router 路由
     */
    public void add(Router router) {
        Set<Router> set = rt.computeIfAbsent(
                router.getIface(), r ->
                        new CopyOnWriteArraySet<>());
        set.add(router);
    }
}
